package com.morn.weibo.http.image;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.morn.weibo.utils.BitmapUtils;

public class ImageDownload {
	private static String TAG = ImageDownload.class.getName();
	public static File cacheDir;
	private DefaultHttpClient httpClient;
	private DownloadImageListener downloadImageListener;
	private boolean isCancelled = false;

	public ImageDownload(Context context, DefaultHttpClient httpClient) {
		this.httpClient = httpClient;
		// if (android.os.Environment.getExternalStorageState().equals(
		// android.os.Environment.MEDIA_MOUNTED))
		// cacheDir = new File(
		// android.os.Environment.getExternalStorageDirectory(),
		// ".fanfou/image");
		// else
		cacheDir = context.getCacheDir();
		if (!cacheDir.exists())
			cacheDir.mkdirs();
	}

	public void stopDownLoad() {
		isCancelled = true;
	}

	// public Bitmap getImageRoundedCorner(String urlStr) {
	//
	// return BitmapUtil.getRoundedCornerBitmap(getImage(urlStr));
	// }

	public interface CancelledListener {
		boolean cancelled();
	};

	public Bitmap getImage(String urlStr, boolean isCompress) {
		Bitmap bitmap = null;
		// String filename = urlStr.substring(urlStr.lastIndexOf("/") + 1,
		// urlStr.length());
		String fileName = String.valueOf(urlStr.hashCode());
		if (!cacheDir.exists())
			cacheDir.mkdirs();
		Log.i(TAG, fileName);
		File cacheFile = new File(cacheDir, fileName);
		InputStream inputStream = null;
		FileOutputStream out = null;
		HttpGet httpGet = null;
		if (cacheFile.exists()) {
			if (isCompress) {
				bitmap = BitmapUtils.compressBitmap(cacheFile, 400, 700);
			} else {
				bitmap = BitmapFactory.decodeFile(cacheFile.getAbsolutePath());
			}
		} else {
			Log.i(TAG, "false");
			try {
				httpGet = new HttpGet(urlStr);
				HttpResponse response = httpClient.execute(httpGet);
				// TODO org.apache.http.NoHttpResponseException: The target
				// server failed to respond

				Log.i("ImageDownload", response.getStatusLine().getStatusCode()
						+ "");
				if (response.getStatusLine().getStatusCode() == 200) {
					HttpEntity entity = response.getEntity();
					inputStream = entity.getContent();
					int size = (int) entity.getContentLength();
					if (downloadImageListener != null) {
						downloadImageListener.getStatus(0, size);
					}
					BufferedInputStream bufferIn = new BufferedInputStream(
							inputStream, 1024);
					ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(
							1024);
					int byte_;
					while ((byte_ = bufferIn.read()) != -1) {
						byteArrayOut.write(byte_);

						if (downloadImageListener != null) {
							downloadImageListener.getStatus(
									byteArrayOut.size(), size);
						}
						if (isCancelled) {
							Log.i(TAG, "image download cancel");
							return null;

						}
					}
					if (byteArrayOut != null && byteArrayOut.size() > 0
							&& byteArrayOut.size() == size) {
						if (!cacheFile.exists()) {
							out = new FileOutputStream(cacheFile);
							byteArrayOut.writeTo(out);
						}
						if (isCompress) {
							bitmap = BitmapUtils.compressBitmap(cacheFile, 400,
									700);
						} else {
							bitmap = BitmapFactory.decodeFile(cacheFile
									.getAbsolutePath());

						}
					}
				}

			} catch (Exception e) {
				Log.e(TAG, "cache=" + cacheFile.getAbsolutePath());
				e.printStackTrace();
			} finally {
				if (httpGet != null) {
					httpGet.abort();
				}

				if (out != null) {
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

		}
		return bitmap;
	}

	public interface DownloadImageListener {
		void getStatus(int i, int size);

	}

	public void setDownloadImageListener(
			DownloadImageListener downloadImageListener) {
		this.downloadImageListener = downloadImageListener;
	}

	public void deleteImage(File file) {
		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteImage(files[i]);
				}
			}
			file.delete();
		} else {
			if (file != null) {
				Log.i(TAG,
						"the file to de deteled is not exist!"
								+ file.getAbsolutePath());
			}
		}
	}

}
